package com.zzyq.pc.web.user.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zzyq.pc.common.StandardDataFormat;
import com.zzyq.pc.common.base.BaseController;
import com.zzyq.pc.common.enums.RoleEnum;
import com.zzyq.pc.common.plugin.db.PageView;
import com.zzyq.pc.common.plugin.shiro.TokenManager;
import com.zzyq.pc.utils.HttpUtils;
import com.zzyq.pc.utils.LoggerUtils;
import com.zzyq.pc.utils.MD5Util;
import com.zzyq.pc.utils.StringUtil;
import com.zzyq.pc.utils.UUIDUtils;
import com.zzyq.pc.web.configure.model.Company;
import com.zzyq.pc.web.configure.model.Depart;
import com.zzyq.pc.web.configure.service.ICompanyService;
import com.zzyq.pc.web.configure.service.IDepartService;
import com.zzyq.pc.web.user.model.Permission;
import com.zzyq.pc.web.user.model.Role;
import com.zzyq.pc.web.user.model.User;
import com.zzyq.pc.web.user.service.IUserService;

/**
 * 
 * <p>
 * 
 * @Title: UserController.java
 * @Description: 用户管理
 * @author: Sywd丶吴迪
 * @date: 2017年9月11日 上午9:55:52
 * @version V1.0
 *          <p>
 */
@Controller
@RequestMapping(value = "/user/", produces = "application/json;charset=UTF-8")
public class UserController extends BaseController {
    @Autowired
    private IUserService userService;

    @Autowired
    private IDepartService departService;

    @Autowired
    private ICompanyService companyService;

    /**
     * 查询用户列表
     */
    @ResponseBody
    @RequestMapping("query")
    public String query(HttpServletRequest httpRequest, HttpServletResponse response, Integer pageIndex,
            Integer pageSize, User user, Integer departId) {
        List<User> users = new ArrayList<>();
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, users);
        PageView pageView = null;
        user = user == null ? new User() : user;
        try {
            // 设置分页参数
            if (pageIndex == null || pageIndex <= 0) {
                pageIndex = 1;
            }
            if (pageSize == null || pageSize <= 0) {
                pageSize = 10;
            }
            pageView = new PageView(pageSize, pageIndex);
            // 取出最大权限级别分数
            // 用户只能查询比自己权限小的用户
            User activeUser = TokenManager.getUser();
            Role activeRole = activeUser.getMaxRole();
            // 若不是管理员，则只能查看本部门
            if (activeUser.getDepart().getDepartId() != -1
                    && !activeRole.getRoleEnum().equals(RoleEnum.User_Com.getRole())) {
                departId = activeUser.getDepart().getDepartId();
            }
            // 判断departId是否有效
            Depart qDepart = new Depart();
            qDepart.setCompanyId(activeUser.getCompany().getCompanyId());
            List<Depart> departs = departService.selectList(null, qDepart);
            boolean flag = false;
            for (Depart depart : departs) {
                if (departId != null && (departId == -1 || departId.intValue() == depart.getDepartId().intValue())) {
                    flag = true;
                    break;
                }
            }
            // 无效的departId,赋值null
            if (!flag) {
                departId = null;
            }
            User qUser = new User();
            qUser.getRoles().add(activeRole);
            qUser.getDepart().setDepartId(departId);
            qUser.getCompany().setCompanyId(activeUser.getCompany().getCompanyId());
            qUser.setUserAccount(user.getUserAccount());
            qUser.setUserPhone(user.getUserPhone());
            qUser.setUserName(transString(httpRequest, user.getUserName()));
            users = userService.selectAsList(pageView, qUser);
            // 查询出角色权限
            for (User repUser : users) {
                List<Role> roles = userService.findRoles(repUser.getUserId());
                repUser.setRoles(roles);
                // 查询权限
                List<Permission> permissions = userService.findPermissions(repUser.getUserId());
                repUser.setPermissions(permissions);
            }
            // 加入页码和总数
            format.setPageIndex(pageView.getPageNow());
            format.setPageSize(pageView.getPageSize());
            format.setTotalPages(pageView.getPageCount());
            format.setTotalRecords(pageView.getRowCount());
            return HttpUtils.formatData(format, CODE_OK, MSG_OK, users);
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtils.fmtError(getClass(), "查询用户列表异常%s", e.getMessage());
            return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, users);
        }
    }

    /**
     * 查询团体管理员用户
     */
    @ResponseBody
    @RequestMapping("admin/query")
    public String adminQuery(HttpServletRequest httpRequest, HttpServletResponse response, Integer pageIndex,
            Integer pageSize, User user, Integer companyId) {
        List<User> users = new ArrayList<>();
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, users);
        PageView pageView = null;
        user = user == null ? new User() : user;
        try {
            // 设置分页参数
            if (pageIndex == null || pageIndex <= 0) {
                pageIndex = 1;
            }
            if (pageSize == null || pageSize <= 0) {
                pageSize = 10;
            }
            pageView = new PageView(pageSize, pageIndex);
            // 取出最大权限级别分数
            // 用户只能查询比自己权限小的用户
            User activeUser = TokenManager.getUser();
            Role activeRole = activeUser.getMaxRole();
            User qUser = new User();
            qUser.getRoles().add(activeRole);
            qUser.getDepart().setDepartId(-1);
            qUser.getCompany().setCompanyId(companyId);
            qUser.setUserAccount(user.getUserAccount());
            qUser.setUserPhone(user.getUserPhone());
            qUser.setUserName(transString(httpRequest, user.getUserName()));
            users = userService.selectAsList(pageView, qUser);
            // 加入页码和总数
            format.setPageIndex(pageView.getPageNow());
            format.setPageSize(pageView.getPageSize());
            format.setTotalPages(pageView.getPageCount());
            format.setTotalRecords(pageView.getRowCount());
            return HttpUtils.formatData(format, CODE_OK, MSG_OK, users);
        } catch (Exception e) {
            e.printStackTrace();
            LoggerUtils.fmtError(getClass(), "查询管理员列表异常%s", e.getMessage());
            return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, users);
        }
    }

    /**
     * 添加普通用户(与部门关联的团体用户)
     */
    @ResponseBody
    @RequestMapping("add")
    public String add(HttpServletRequest httpRequest, HttpServletResponse response, User user, Integer departId,
            Integer level) {
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
        // 判断传入参数是否合理
        // 账户/手机号不能为空
        if (user == null || StringUtils.isBlank(user.getUserAccount()) || StringUtils.isBlank(user.getUserPhone())
                || !StringUtil.isPhoneLegal(user.getUserPhone())) {
            return HttpUtils.formatData(format, CODE_ERROR_PARAMS, "请输入正确的帐号/手机号", null);
        }
        // 当输入了手机号时可以不设置密码,密码默认为手机号后六位
        // 未输入手机号时必须手动设置初始密码
        if (StringUtils.isBlank(user.getUserPwd())) {
            if (!StringUtils.isBlank(user.getUserPhone())) {
                String pwd = user.getUserPhone().substring(user.getUserPhone().length() - 6,
                        user.getUserPhone().length());
                user.setUserPwd(pwd);
            } else {
                return HttpUtils.formatData(format, CODE_ERROR_PARAMS, "请输入密码", null);
            }
        }
        // 账号名称
        if (StringUtils.isBlank(user.getUserName())) {
            return HttpUtils.formatData(format, CODE_ERROR_PARAMS, "账户名称不能为空", null);
        }
        user.setUserName(transString(httpRequest, user.getUserName()));
        user.setUserJob(transString(httpRequest, user.getUserJob()));
        // 查询相同的信息
        List<User> same = userService.selectSameList(user);
        if (!(same == null || same.isEmpty())) {
            return HttpUtils.formatData(format, CODE_ERROR_SAME, MSG_ERROR_SAME, null);
        }
        // 校验操作人员权限和部门有效性
        User activeUser = TokenManager.getUser();
        // 取出在线操作用户的部门和团体ID，权限
        int activeCompanyId = activeUser.getCompany().getCompanyId();
        int activeDepartId = activeUser.getDepart().getDepartId();
        Role activeRole = activeUser.getMaxRole();
        // 这里对添加的用户级别进行校验
        // 级别不对则赋予普通用户级别
        if (level == null || level < 0) {
            level = RoleEnum.User_Simple.getGrade();
        }
        // 新建一个角色信息
        Role addRole = null;
        for (RoleEnum roleEnum : RoleEnum.values()) {
            // 这里遍历所有角色，若级别分数值相等则赋予这一角色,若没有遍历到则代表角色级别不对
            if (roleEnum.getGrade().intValue() == level) {
                addRole = roleEnum.transToRole();
                break;
            }
        }
        // 不能添加比自己级别高的用户
        if (level <= activeRole.getRoleGrade().intValue() || addRole == null
                || addRole.getRoleGrade().intValue() <= activeRole.getRoleGrade().intValue()) {
            return HttpUtils.formatData(format, CODE_ERROR_PARAMS, "请输入正确用户权限等级", null);
        }
        // 通过角色信息判断新增的用户是否符合自己权限之内
        // 团体管理员/团体领导角色---可添加比自己权限低的任何部门的帐号
        if (activeRole.getRoleEnum().equals(RoleEnum.Admin_Com.getRole())
                || activeRole.getRoleEnum().equals(RoleEnum.User_Com.getRole())) {
            Depart qDepart = departService.selectById(departId);
            if (qDepart == null
                    || qDepart.getCompanyId().intValue() != activeUser.getCompany().getCompanyId().intValue()) {
                return HttpUtils.formatData(format, CODE_ERROR_PARAMS, "请输入正确的部门信息", null);
            }
        } else {
            // 当属于某部门时的二级管理员时，只允许添加本部门的人员信息,则传入的参数无效
            departId = activeDepartId;
        }
        // 设置团体ID
        user.getCompany().setCompanyId(activeCompanyId);
        // 设置部门信息
        user.getDepart().setDepartId(departId);
        // 设置角色信息
        user.getRoles().add(addRole);
        // 设置一些新增用户时的默认参数
        user.setIsDelete(user.getIsDelete() == null ? 0 : user.getIsDelete());
        user.setSingleLogin(user.getSingleLogin() == null ? 0 : user.getSingleLogin());
        user.setUserSys(user.getUserSys() == null ? 0 : user.getUserSys());
        user.setUserType(user.getUserType() == null ? 0 : user.getUserType());
        // 加密密码
        String salt = UUIDUtils.getUUID();
        user.setUserSalt(salt);
        user.setUserPwd(MD5Util.getShiroMd5(user.getUserPwd(), salt));
        // 新增操作
        boolean result = userService.addUser(user);
        if (result) {
            // 新增成功
            return HttpUtils.formatData(format, CODE_OK, MSG_OK, null);
        }
        return HttpUtils.formatData(format, CODE_ERROR, MSG_ERROR, null);
    }

    /**
     * 添加团体管理员用户
     */
    @ResponseBody
    @RequestMapping("admin/add")
    public String adminAdd(HttpServletRequest httpRequest, HttpServletResponse response, User user, Integer companyId) {
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
        try {
            // 判断传入参数是否合理
            // 账户/手机号不能为空
            if (user == null || (StringUtils.isBlank(user.getUserAccount())
                    && (StringUtils.isBlank(user.getUserPhone()) || !StringUtil.isPhoneLegal(user.getUserPhone())))) {
                return HttpUtils.formatData(format, CODE_ERROR_PARAMS, "请输入正确的帐号/手机号", null);
            }
            // 当输入了手机号时可以不设置密码,密码默认为手机号后六位
            // 未输入手机号时必须手动设置初始密码
            if (StringUtils.isBlank(user.getUserPwd())) {
                if (!StringUtils.isBlank(user.getUserPhone())) {
                    String pwd = user.getUserPhone().substring(user.getUserPhone().length() - 6,
                            user.getUserPhone().length());
                    user.setUserPwd(pwd);
                } else {
                    return HttpUtils.formatData(format, CODE_ERROR_PARAMS, "请输入密码", null);
                }
            }
            // 账号名称
            if (StringUtils.isBlank(user.getUserName())) {
                user.setUserName(user.getUserAccount());
            }
            user.setUserName(transString(httpRequest, user.getUserName()));
            // 查询相同的信息
            List<User> same = userService.selectSameList(user);
            if (!(same == null || same.isEmpty())) {
                return HttpUtils.formatData(format, CODE_ERROR_SAME, MSG_ERROR_SAME, null);
            }
            Role addRole = null;
            // 团体检测，-1表示添加系统管理员，否则需要查询是否存在此ID的团体
            // 给新增的用户赋予角色信息
            if (companyId != null && companyId != -1) {
                Company company = companyService.selectById(companyId);
                if (company == null) {
                    return HttpUtils.formatData(format, CODE_ERROR_PARAMS, "请输入正确的组织信息", null);
                }
                User qUser = new User();
                qUser.getCompany().setCompanyId(companyId);
                qUser.getDepart().setDepartId(-1);
                List<User> users = userService.selectAsList(null, qUser);
                if (users != null && users.size() >= 3) {
                    return HttpUtils.formatData(format, CODE_ERROR, "管理员数量已达到上限3个", null);
                }
                addRole = RoleEnum.Admin_Com.transToRole();
            } else {
                companyId = -1;
                addRole = RoleEnum.Admin_Sys.transToRole();
            }
            // 设置团体ID
            user.getCompany().setCompanyId(companyId);
            // 设置部门信息
            user.getDepart().setDepartId(-1);
            // 设置角色信息
            user.getRoles().add(addRole);
            // 设置一些新增用户时的默认参数
            user.setIsDelete(user.getIsDelete() == null ? 0 : user.getIsDelete());
            user.setSingleLogin(user.getSingleLogin() == null ? 0 : user.getSingleLogin());
            user.setUserSys(user.getUserSys() == null ? 0 : user.getUserSys());
            user.setUserType(user.getUserType() == null ? 0 : user.getUserType());
            // 加密密码
            String salt = UUIDUtils.getUUID();
            user.setUserSalt(salt);
            user.setUserPwd(MD5Util.getShiroMd5(user.getUserPwd(), salt));
            // 新增操作
            boolean result = userService.addUser(user);
            if (result) {
                // 新增成功
                return HttpUtils.formatData(format, CODE_OK, MSG_OK, null);
            }
            return HttpUtils.formatData(format, CODE_ERROR, MSG_ERROR, null);
        } catch (Exception e) {
            e.printStackTrace();
            return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
        }
    }

    /**
     * 修改普通用户(与部门关联的团体用户)
     */
    @ResponseBody
    @RequestMapping("update")
    public String update(HttpServletRequest httpRequest, HttpServletResponse response, User user, Integer departId,
            Integer level) {
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
        try {

            // 判断传入参数是否合理
            if (departId == null || level == null) {
                return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
            }
            if (user == null || user.getUserId() == null
                    || (StringUtils.isBlank(user.getUserPhone()) || !StringUtil.isPhoneLegal(user.getUserPhone()))) {
                return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
            }
            // 账号名称
            if (StringUtils.isBlank(user.getUserName())) {
                return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
            }
            user.setUserName(transString(httpRequest, user.getUserName()));
            user.setUserJob(transString(httpRequest, user.getUserJob()));
            User activeUser = TokenManager.getUser();
            Role activeRole = activeUser.getMaxRole();
            User qUser = new User();
            qUser.setUserId(user.getUserId());
            qUser.getRoles().add(activeRole);
            boolean isUpdateRole = false;
            // 系统管理员级别
            if (activeRole.getRoleGrade().intValue() <= RoleEnum.Admin_Sys.getGrade().intValue()) {
                qUser.getDepart().setDepartId(-1);
                // 系统管理员更改的账户不属于任何部门
                departId = -1;
            } else if (activeRole.getRoleGrade().intValue() <= RoleEnum.User_Com.getGrade().intValue()) {
                // 团体领导级别
                qUser.getCompany().setCompanyId(activeUser.getCompany().getCompanyId());
                // 查询更改后的部门是否有效,必须属于此团体
                Depart qDepart = new Depart();
                qDepart.setCompanyId(activeUser.getCompany().getCompanyId());
                List<Depart> departs = departService.selectList(null, qDepart);
                boolean flag = false;
                for (Depart depart : departs) {
                    if (depart.getDepartId().intValue() == departId.intValue()) {
                        flag = true;
                        break;
                    }
                }
                // 部门ID不符
                if (!flag) {
                    return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
                }
                isUpdateRole = true;
            } else {
                // 部门负责人级别
                qUser.getDepart().setDepartId(activeUser.getDepart().getDepartId());
                qUser.getCompany().setCompanyId(activeUser.getCompany().getCompanyId());
                // 只能修改为本部门的
                departId = activeUser.getDepart().getDepartId();
            }
            List<User> users = userService.selectAsList(null, qUser);
            if (users == null || users.size() != 1) {
                return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
            }
            // 取出原User信息
            User oUser = users.get(0);
            // 判断手机号的更改
            /*
             * if (StringUtils.isNotBlank(oUser.getUserPhone()) &&
             * StringUtils.isNotBlank(user.getUserPhone()) &&
             * !oUser.getUserPhone().equals(user.getUserPhone())) { // 重置密码
             * String pwd =
             * user.getUserPhone().substring(user.getUserPhone().length() - 6,
             * user.getUserPhone().length());
             * user.setUserPwd(MD5Util.getShiroMd5(pwd, oUser.getUserSalt())); }
             */
            user.getDepart().setDepartId(departId);
            // 判断并修改用户的角色
            if (isUpdateRole) {
                // 先查出原用户的所有角色信息
                List<Role> roles = userService.findRoles(oUser.getUserId());
                oUser.setRoles(roles);
                if (level == null || level < 0) {
                    level = oUser.getMaxRole().getRoleGrade();
                }
                // 修改用户的角色
                // 新建一个角色信息
                Role addRole = null;
                for (RoleEnum roleEnum : RoleEnum.values()) {
                    // 这里遍历所有角色，若级别分数值相等则赋予这一角色,若没有遍历到则代表角色级别不对
                    if (roleEnum.getGrade().intValue() == level) {
                        addRole = roleEnum.transToRole();
                        break;
                    }
                }
                // 不能修改比自己级别高的用户
                if (level <= activeRole.getRoleGrade().intValue() || addRole == null
                        || addRole.getRoleGrade().intValue() <= activeRole.getRoleGrade().intValue()) {
                    return HttpUtils.formatData(format, CODE_ERROR_PARAMS, "请输入正确用户权限等级", null);
                }
                user.getRoles().add(addRole);
            }
            // 检查是否存在未处理的一系列任务
            boolean isTasks = userService.selectTasks(user.getUserId());
            if (isTasks) {
                return HttpUtils.formatData(format, CODE_ERROR_OTHER, "该用户存在未处理的任务，请检查", null);
            }
            // 修改用户
            boolean result = userService.updateUser(user);
            if (!result) {
                return HttpUtils.formatData(format, CODE_ERROR, MSG_ERROR, null);
            }
            // 用户下线
            unLine(httpRequest, response, oUser);
            return HttpUtils.formatData(format, CODE_OK, MSG_OK, null);
        } catch (Exception e) {
            e.printStackTrace();
            return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
        }
    }

    /**
     * 根据用户ID删除用户
     */
    @ResponseBody
    @RequestMapping("delete")
    public String delete(HttpServletRequest httpRequest, HttpServletResponse response, Integer userId) {
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
        try {
            if (userId == null) {
                return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
            }
            User activeUser = TokenManager.getUser();
            Role activeRole = activeUser.getMaxRole();
            User qUser = new User();
            qUser.setUserId(userId);
            qUser.getRoles().add(activeRole);
            // 系统管理员级别
            if (activeRole.getRoleGrade().intValue() <= RoleEnum.Admin_Sys.getGrade().intValue()) {
                qUser.getDepart().setDepartId(-1);
            } else if (activeRole.getRoleGrade().intValue() <= RoleEnum.User_Com.getGrade().intValue()) {
                qUser.getCompany().setCompanyId(activeUser.getCompany().getCompanyId());
            } else {
                qUser.getDepart().setDepartId(activeUser.getDepart().getDepartId());
                qUser.getCompany().setCompanyId(activeUser.getCompany().getCompanyId());
            }
            List<User> users = userService.selectAsList(null, qUser);
            if (users == null || users.size() != 1) {
                return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
            }
            // 检查是否存在未处理的一系列任务
            boolean isTasks = userService.selectTasks(userId);
            if (isTasks) {
                return HttpUtils.formatData(format, CODE_ERROR_OTHER, "该用户存在未处理的任务，请检查", null);
            }
            boolean result = userService.deleteById(userId);
            if (!result) {
                return HttpUtils.formatData(format, CODE_ERROR, MSG_ERROR, null);
            }
            // 删除后通知下线
            unLine(httpRequest, response, users.get(0));
            return HttpUtils.formatData(format, CODE_OK, MSG_OK, null);
        } catch (Exception e) {
            return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
        }
    }

    /**
     * 重置用户密码
     */
    @ResponseBody
    @RequestMapping("resetPwd")
    public String resetPwd(HttpServletRequest httpRequest, HttpServletResponse response, Integer userId) {
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
        try {
            if (userId == null) {
                return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
            }
            User activeUser = TokenManager.getUser();
            Role activeRole = activeUser.getMaxRole();
            User qUser = new User();
            qUser.setUserId(userId);
            qUser.getRoles().add(activeRole);
            // 系统管理员级别
            if (activeRole.getRoleGrade().intValue() <= RoleEnum.Admin_Sys.getGrade().intValue()) {
                qUser.getDepart().setDepartId(-1);
            } else if (activeRole.getRoleGrade().intValue() <= RoleEnum.User_Com.getGrade().intValue()) {
                qUser.getCompany().setCompanyId(activeUser.getCompany().getCompanyId());
            } else {
                qUser.getDepart().setDepartId(activeUser.getDepart().getDepartId());
                qUser.getCompany().setCompanyId(activeUser.getCompany().getCompanyId());
            }
            List<User> users = userService.selectAsList(null, qUser);
            if (users == null || users.size() != 1) {
                return HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
            }
            User user = users.get(0);
            // 重置密码
            String phone6 = user.getUserPhone().substring(user.getUserPhone().length() - 6,
                    user.getUserPhone().length());
            String pwd = MD5Util.getShiroMd5(phone6, user.getUserSalt());
            boolean result = userService.updatePwd(userId, pwd);
            if (!result) {
                return HttpUtils.formatData(format, CODE_ERROR, MSG_ERROR, null);
            }
            // 删除后通知下线
            unLine(httpRequest, response, users.get(0));
            return HttpUtils.formatData(format, CODE_OK, MSG_OK, null);
        } catch (Exception e) {
            return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
        }
    }

    /**
     * 此接口是用户自行修改密码,修改密码后，自动帮助用户重新登录
     * 
     * @param userId
     *            用户ID
     * @param pwd1
     *            用户原密码
     * @param pwd2
     *            用户新密码
     * @return
     */
    @ResponseBody
    @RequestMapping("modifyPwd")
    public String modifyPwd(HttpServletRequest httpRequest, HttpServletResponse response, String pwd1, String pwd2) {
        StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
        try {
            if (pwd1 == null || pwd2 == null) {
                HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
            }
            // 查出用户的信息，原密码、盐值等
            User user = TokenManager.getUser();
            if (user == null) {
                HttpUtils.formatData(format, CODE_ERROR_PARAMS, MSG_ERROR_PARAMS, null);
            }
            // 校验输入原密码是否为原密码
            String pwd1s = MD5Util.getShiroMd5(pwd1, user.getUserSalt());
            if (!user.getUserPwd().equals(pwd1s)) {
                return HttpUtils.formatData(format, CODE_ERROR_OTHER, "请输入正确的原密码", null);
            }
            // 更新密码到数据库
            String pwd2s = MD5Util.getShiroMd5(pwd2, user.getUserSalt());
            boolean result = userService.updatePwd(user.getUserId(), pwd2s);
            if (!result) {
                return HttpUtils.formatData(format, CODE_ERROR, MSG_ERROR, null);
            }
            TokenManager.logout();
            // 操作成功后直接重新登录
            /*
             * String account = StringUtils.isBlank(user.getUserAccount()) ?
             * user.getUserPhone() : user.getUserAccount(); ZzyqToken token =
             * new ZzyqToken(account, pwd2); Subject subject =
             * SecurityUtils.getSubject(); subject.login(token);
             */
            return HttpUtils.formatData(format, CODE_OK, MSG_OK, null);
        } catch (Exception e) {
            return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
        }
    }
}
